﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System;

namespace JavaScriptSerializerTest
{
	public static class SerializationExtensions
	{       
        
		/// <summary>
		/// Serializes the object to a JSON formatted string.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="obj">The object being converted to JSON.</param>
		/// <returns></returns>
		public static string ToJSON<T>(this T obj)
		{
			MemoryStream stream = new MemoryStream();

			try
			{
				//serialize data to a stream, then to a JSON string
				DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof(T));
				jsSerializer.WriteObject(stream, obj);

				return Encoding.UTF8.GetString(stream.ToArray());
			}
			finally
			{
				stream.Close();
				stream.Dispose();
			}
		}
	}
}
